package com.example.screenshot_service

import android.animation.Animator
import android.animation.AnimatorListenerAdapter
import android.animation.AnimatorSet
import android.animation.ObjectAnimator
import android.animation.ValueAnimator
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.app.Service
import android.content.Context
import android.content.Intent
import android.graphics.PixelFormat
import android.os.Build
import android.os.Handler
import android.os.IBinder
import android.os.Looper
import android.util.DisplayMetrics
import android.util.Log
import android.view.Gravity
import android.view.LayoutInflater
import android.view.MotionEvent
import android.view.View
import android.view.ViewConfiguration
import android.view.WindowManager
import android.view.animation.DecelerateInterpolator
import android.view.animation.OvershootInterpolator
import android.widget.ImageView
import android.widget.Toast
import androidx.core.app.NotificationCompat
import com.example.patchouli_knowledge.MainActivity
import com.example.patchouli_knowledge.R
import kotlin.math.abs
import kotlin.math.pow
import kotlin.math.sqrt

/**
 * 智能悬浮球服务 - 类似搜题酱的精美悬浮球
 * 
 * 功能特点：
 * 1. 精美的渐变设计和动画效果
 * 2. 智能边缘吸附
 * 3. 拖拽交互
 * 4. 点击截图功能
 * 5. 集成现有的OCR和上传流程
 */
class SmartFloatingBallService : Service() {
    
    companion object {
        private const val TAG = "SmartFloatingBall"
        private const val NOTIFICATION_ID = 2001
        private const val CHANNEL_ID = "SmartFloatingBallChannel"
        private var isServiceRunning = false
        
        // 动画时长
        private const val ANIMATION_DURATION = 300L
        private const val PULSE_DURATION = 1000L
        private const val AUTO_HIDE_DELAY = 3000L
        
        // 边缘吸附距离
        private const val EDGE_SNAP_DISTANCE = 100
        
        fun isRunning(): Boolean = isServiceRunning
    }
    
    // UI组件
    private lateinit var windowManager: WindowManager
    private lateinit var floatingBallView: View
    private lateinit var ballIcon: ImageView
    
    // 屏幕信息
    private var screenWidth = 0
    private var screenHeight = 0
    private val ballSize by lazy { resources.getDimensionPixelSize(R.dimen.smart_floating_ball_size) }
    private val edgeMargin by lazy { resources.getDimensionPixelSize(R.dimen.floating_ball_margin) }
    
    // 触摸和拖拽
    private var isDragging = false
    private var initialX = 0
    private var initialY = 0
    private var initialTouchX = 0f
    private var initialTouchY = 0f
    private var lastMoveTime = 0L
    
    // 动画和处理器
    private val mainHandler = Handler(Looper.getMainLooper())
    private var autoHideRunnable: Runnable? = null
    
    // 状态管理
    private var isVisible = true
    private var isAnimating = false
    
    override fun onCreate() {
        super.onCreate()
        Log.d(TAG, "智能悬浮球服务启动")
        
        windowManager = getSystemService(Context.WINDOW_SERVICE) as WindowManager
        initScreenSize()
        createNotificationChannel()
        startForeground(NOTIFICATION_ID, createNotification())
        
        setupFloatingBall()
        isServiceRunning = true
    }
    
    /**
     * 初始化屏幕尺寸
     */
    private fun initScreenSize() {
        val displayMetrics = DisplayMetrics()
        windowManager.defaultDisplay.getMetrics(displayMetrics)
        screenWidth = displayMetrics.widthPixels
        screenHeight = displayMetrics.heightPixels
        Log.d(TAG, "屏幕尺寸: ${screenWidth}x${screenHeight}")
    }
    
    /**
     * 创建通知渠道
     */
    private fun createNotificationChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val channel = NotificationChannel(
                CHANNEL_ID,
                "智能悬浮球",
                NotificationManager.IMPORTANCE_LOW
            ).apply {
                description = "提供智能截图和知识管理功能"
                setShowBadge(false)
            }
            
            val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
            notificationManager.createNotificationChannel(channel)
        }
    }
    
    /**
     * 创建前台服务通知
     */
    private fun createNotification(): Notification {
        val intent = Intent(this, MainActivity::class.java)
        val pendingIntent = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_IMMUTABLE)
        } else {
            PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT)
        }

        return NotificationCompat.Builder(this, CHANNEL_ID)
            .setContentTitle("知拾智能助手")
            .setContentText("悬浮球已启动，点击即可智能截图")
            .setSmallIcon(R.mipmap.launcher_icon)
            .setContentIntent(pendingIntent)
            .setPriority(NotificationCompat.PRIORITY_LOW)
            .setOngoing(true)
            .build()
    }
    
    /**
     * 设置悬浮球
     */
    private fun setupFloatingBall() {
        // 加载布局
        floatingBallView = LayoutInflater.from(this)
            .inflate(R.layout.smart_floating_ball_layout, null)
        
        // 获取子视图
        ballIcon = floatingBallView.findViewById(R.id.smart_floating_ball_icon)
        
        // 设置初始透明度
        floatingBallView.alpha = 0.9f
        
        // 设置触摸监听
        setupTouchListener()
        
        // 设置窗口参数
        val params = createWindowLayoutParams()
        
        // 设置初始位置（右边缘中央）
        params.x = screenWidth - ballSize - edgeMargin
        params.y = (screenHeight - ballSize) / 2
        
        try {
            windowManager.addView(floatingBallView, params)
            Log.d(TAG, "悬浮球添加成功，位置: (${params.x}, ${params.y})")
            
            // 显示入场动画
            showEntranceAnimation()
            
        } catch (e: Exception) {
            Log.e(TAG, "添加悬浮球失败: ${e.message}")
        }
    }
    
    /**
     * 创建窗口布局参数
     */
    private fun createWindowLayoutParams(): WindowManager.LayoutParams {
        return WindowManager.LayoutParams(
            ballSize,
            ballSize,
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
                WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY
            else
                WindowManager.LayoutParams.TYPE_PHONE,
            WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE or
                    WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL or
                    WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS,
            PixelFormat.TRANSLUCENT
        ).apply {
            gravity = Gravity.START or Gravity.TOP
        }
    }
    
    /**
     * 设置触摸监听器
     */
    private fun setupTouchListener() {
        // 同时在容器和图标上设置触摸监听器
        floatingBallView.setOnTouchListener { v, event ->
            try {
                Log.d(TAG, "容器触摸事件: ${event.action}")
                val params = v.layoutParams as WindowManager.LayoutParams
                
                when (event.action and MotionEvent.ACTION_MASK) {
                    MotionEvent.ACTION_DOWN -> {
                        Log.d(TAG, "容器 ACTION_DOWN detected")
                        handleTouchDown(event, params)
                        return@setOnTouchListener true
                    }
                    MotionEvent.ACTION_MOVE -> {
                        handleTouchMove(event, params)
                        return@setOnTouchListener true
                    }
                    MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> {
                        Log.d(TAG, "容器 ACTION_UP/CANCEL detected")
                        handleTouchUp(event, params)
                        return@setOnTouchListener true
                    }
                }
                true
            } catch (e: Exception) {
                Log.e(TAG, "容器触摸事件处理异常: ${e.message}")
                false
            }
        }
        
        // 在图标上也设置触摸监听器作为备用
        ballIcon.setOnTouchListener { v, event ->
            try {
                Log.d(TAG, "图标触摸事件: ${event.action}")
                val params = floatingBallView.layoutParams as WindowManager.LayoutParams
                
                when (event.action and MotionEvent.ACTION_MASK) {
                    MotionEvent.ACTION_DOWN -> {
                        Log.d(TAG, "图标 ACTION_DOWN detected")
                        handleTouchDown(event, params)
                        return@setOnTouchListener true
                    }
                    MotionEvent.ACTION_MOVE -> {
                        handleTouchMove(event, params)
                        return@setOnTouchListener true
                    }
                    MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> {
                        Log.d(TAG, "图标 ACTION_UP/CANCEL detected")
                        handleTouchUp(event, params)
                        return@setOnTouchListener true
                    }
                }
                true
            } catch (e: Exception) {
                Log.e(TAG, "图标触摸事件处理异常: ${e.message}")
                false
            }
        }
    }
    
    /**
     * 处理触摸按下
     */
    private fun handleTouchDown(event: MotionEvent, params: WindowManager.LayoutParams) {
        isDragging = false
        initialX = params.x
        initialY = params.y
        initialTouchX = event.rawX
        initialTouchY = event.rawY
        lastMoveTime = System.currentTimeMillis()
        
        // 取消自动隐藏
        autoHideRunnable?.let { mainHandler.removeCallbacks(it) }
        
        // 显示活跃状态
        showActiveState()
        
        Log.d(TAG, "触摸开始: 触摸位置(${event.rawX}, ${event.rawY}), 悬浮球位置(${params.x}, ${params.y})")
    }
    
    /**
     * 处理触摸移动
     */
    private fun handleTouchMove(event: MotionEvent, params: WindowManager.LayoutParams) {
        val deltaX = event.rawX - initialTouchX
        val deltaY = event.rawY - initialTouchY
        val distance = sqrt(deltaX.pow(2) + deltaY.pow(2))
        
        // 使用较小的拖拽阈值，让拖拽更容易触发
        val dragThreshold = 15f // 降低阈值到15像素
        
        // 判断是否开始拖拽
        if (!isDragging && distance > dragThreshold) {
            isDragging = true
            Log.d(TAG, "开始拖拽，移动距离: $distance")
        }
        
        if (isDragging) {
            // 更新位置
            val newX = (initialX + deltaX).toInt()
            val newY = (initialY + deltaY).toInt()
            
            // 限制在屏幕范围内
            params.x = newX.coerceIn(-ballSize / 2, screenWidth - ballSize / 2)
            params.y = newY.coerceIn(0, screenHeight - ballSize)
            
            try {
                windowManager.updateViewLayout(floatingBallView, params)
                lastMoveTime = System.currentTimeMillis()
                Log.v(TAG, "位置更新: (${params.x}, ${params.y})")
            } catch (e: Exception) {
                Log.e(TAG, "更新位置失败: ${e.message}")
            }
        }
    }
    
    /**
     * 处理触摸释放
     */
    private fun handleTouchUp(event: MotionEvent, params: WindowManager.LayoutParams) {
        if (isDragging) {
            // 拖拽结束，执行边缘吸附
            snapToEdge(params)
        } else {
            // 点击事件，执行截图
            performScreenshot()
        }
        
        isDragging = false
        hideActiveState()
        scheduleAutoHide()
        
        Log.d(TAG, "触摸结束，是否拖拽: $isDragging")
    }
    
    /**
     * 边缘吸附动画
     */
    private fun snapToEdge(params: WindowManager.LayoutParams) {
        val centerX = params.x + ballSize / 2
        val targetX = if (centerX < screenWidth / 2) {
            // 吸附到左边
            edgeMargin
        } else {
            // 吸附到右边
            screenWidth - ballSize - edgeMargin
        }
        
        // 创建位置动画
        val animator = ValueAnimator.ofInt(params.x, targetX).apply {
            duration = ANIMATION_DURATION
            interpolator = OvershootInterpolator(0.5f)
            addUpdateListener { animation ->
                params.x = animation.animatedValue as Int
                windowManager.updateViewLayout(floatingBallView, params)
            }
        }
        
        animator.start()
        Log.d(TAG, "边缘吸附: ${params.x} -> $targetX")
    }
    
    /**
     * 执行截图
     */
    private fun performScreenshot() {
        Log.d(TAG, "悬浮球触发截图操作")
        
        // 显示点击反馈动画
        showClickFeedback()
        
        // 检查持久截屏服务状态
        if (PersistentScreenCaptureService.isRunning()) {
            // 服务已运行，直接触发截屏
            triggerPersistentCapture()
        } else {
            // 服务未运行，需要先启动服务和权限授权
            requestCapturePermissionAndStart()
        }
        
        // 显示提示
        Toast.makeText(this, "正在触发截图...", Toast.LENGTH_SHORT).show()
    }
    
    /**
     * 触发持久截屏服务执行截屏
     */
    private fun triggerPersistentCapture() {
        try {
            val captureIntent = Intent(this, PersistentScreenCaptureService::class.java).apply {
                action = "CAPTURE_SCREEN"
                putExtra("source", "smart_floating_ball")
            }
            startService(captureIntent)
            
            Log.d(TAG, "截屏请求已发送到持久服务")
        } catch (e: Exception) {
            Log.e(TAG, "触发持久截屏失败: ${e.message}")
            // 回退到传统方式
            sendScreenshotCommand()
        }
    }
    
    /**
     * 请求截屏权限并启动服务
     */
    private fun requestCapturePermissionAndStart() {
        try {
            // 通过MainActivity请求MediaProjection权限
            val intent = Intent(this, MainActivity::class.java).apply {
                action = "REQUEST_CAPTURE_PERMISSION"
                flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_SINGLE_TOP
                putExtra("source", "smart_floating_ball")
                putExtra("startPersistentService", true)
            }
            startActivity(intent)
            
            Log.d(TAG, "权限请求已发送")
        } catch (e: Exception) {
            Log.e(TAG, "请求权限失败: ${e.message}")
            // 回退到传统方式
            sendScreenshotCommand()
        }
    }
    
    /**
     * 发送截图命令到Flutter（回退方案）
     */
    private fun sendScreenshotCommand() {
        try {
            // 通过Intent启动MainActivity并传递截图命令
            val intent = Intent(this, MainActivity::class.java).apply {
                action = "SMART_SCREENSHOT_ACTION"
                flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_SINGLE_TOP
                putExtra("command", "screenshot")
                putExtra("source", "smart_floating_ball")
            }
            startActivity(intent)
            
            Log.d(TAG, "截图命令已发送")
        } catch (e: Exception) {
            Log.e(TAG, "发送截图命令失败: ${e.message}")
        }
    }
    
    /**
     * 显示入场动画
     */
    private fun showEntranceAnimation() {
        floatingBallView.apply {
            scaleX = 0f
            scaleY = 0f
            alpha = 0f
        }
        
        val scaleAnimator = ObjectAnimator.ofFloat(floatingBallView, "scaleX", 0f, 1.2f, 1f).apply {
            duration = ANIMATION_DURATION
            interpolator = OvershootInterpolator()
        }
        
        val scaleYAnimator = ObjectAnimator.ofFloat(floatingBallView, "scaleY", 0f, 1.2f, 1f).apply {
            duration = ANIMATION_DURATION
            interpolator = OvershootInterpolator()
        }
        
        val alphaAnimator = ObjectAnimator.ofFloat(floatingBallView, "alpha", 0f, 0.9f).apply {
            duration = ANIMATION_DURATION / 2
        }
        
        AnimatorSet().apply {
            playTogether(scaleAnimator, scaleYAnimator, alphaAnimator)
            start()
        }
    }
    
    /**
     * 显示点击反馈动画（简化版）
     */
    private fun showClickFeedback() {
        // 简单的透明度变化反馈
        ballIcon.animate()
            .alpha(0.7f)
            .setDuration(100)
            .withEndAction {
                ballIcon.animate()
                    .alpha(1f)
                    .setDuration(100)
                    .start()
            }
            .start()
    }
    
    /**
     * 显示活跃状态（简化版）
     */
    private fun showActiveState() {
        floatingBallView.animate()
            .alpha(1f)
            .setDuration(100)
            .start()
    }
    
    /**
     * 隐藏活跃状态（简化版）
     */
    private fun hideActiveState() {
        floatingBallView.animate()
            .alpha(0.9f)
            .setDuration(150)
            .start()
    }
    

    
    /**
     * 安排自动隐藏
     */
    private fun scheduleAutoHide() {
        autoHideRunnable?.let { mainHandler.removeCallbacks(it) }
        autoHideRunnable = Runnable {
            if (!isDragging && isVisible) {
                hideFloatingBall()
            }
        }
        mainHandler.postDelayed(autoHideRunnable!!, AUTO_HIDE_DELAY)
    }
    
    /**
     * 隐藏悬浮球
     */
    private fun hideFloatingBall() {
        if (isAnimating) return
        
        isAnimating = true
        isVisible = false
        
        floatingBallView.animate()
            .alpha(0.3f)
            .scaleX(0.8f)
            .scaleY(0.8f)
            .setDuration(ANIMATION_DURATION)
            .setListener(object : AnimatorListenerAdapter() {
                override fun onAnimationEnd(animation: Animator) {
                    isAnimating = false
                }
            })
            .start()
        
        Log.d(TAG, "悬浮球已隐藏")
    }
    
    /**
     * 显示悬浮球
     */
    private fun showFloatingBall() {
        if (isAnimating) return
        
        isAnimating = true
        isVisible = true
        
        floatingBallView.animate()
            .alpha(0.9f)
            .scaleX(1f)
            .scaleY(1f)
            .setDuration(ANIMATION_DURATION)
            .setListener(object : AnimatorListenerAdapter() {
                override fun onAnimationEnd(animation: Animator) {
                    isAnimating = false
                    scheduleAutoHide()
                }
            })
            .start()
        
        Log.d(TAG, "悬浮球已显示")
    }
    
    override fun onBind(intent: Intent?): IBinder? = null
    
    override fun onDestroy() {
        super.onDestroy()
        
        try {
            windowManager.removeView(floatingBallView)
        } catch (e: Exception) {
            Log.e(TAG, "移除悬浮球失败: ${e.message}")
        }
        
        // 清理资源
        mainHandler.removeCallbacksAndMessages(null)
        
        isServiceRunning = false
        Log.d(TAG, "智能悬浮球服务已销毁")
    }
} 